<?php

namespace App\controller;

use App\model\Ban;
use app\model\Item;
use App\model\Mail;
use App\model\Role;
use App\model\Shop;
use app\model\User;
use App\model\UserExchangeLog;
use support\Common;
use support\Constant;
use support\Db;
use Webman\RedisQueue\Redis;
use support\Request;
use support\Response;

class UserController extends CommonController
{
    /**
     * 加入游戏
     * @param Request $request
     * @return Response
     */
    public function login(Request $request)
    {
        $data = $request->postData;
        $data['ip'] = $request->getRealIp();
        print_r($data);
        $uuid = $data['uuid'] ?? '';
        $nickname = $data['nickname'] ?? '';
        $icon = $data['icon'] ?? '';

        $user_model = User::query()->where('uuid', $uuid)->first();

        $is_ban = false;
        if (empty($user_model)) {
            $user_model = new User();
            $user_model->uuid = $uuid;
            $user_model->nickname = $nickname;
            $user_model->icon = $icon;
            $user_model->save();
        } else {
            if ($user_model->is_ban) {
                $is_ban = true;
            }
            //更新nickname
            if ($user_model['nickname'] != $nickname) {
                $user_model->nickname = $nickname;
            }
            //更新头像
            if ($user_model['icon'] != $icon) {
                $user_model->icon = $icon;
            }

            $user_model->save();

            //判断是否封禁ip
            $is_ex = Ban::query()->Where('ip', $data['ip'])->exists();
            if ($is_ex) {
                $is_ban = true;
            }
        }

        Redis::send(Constant::RECORD_USER_LOGIN_LOG, $data);

        return outJson(0, 'ok', ['is_ban' => $is_ban]);
    }

    /***
     *
     * @param Request $request
     * @return Response
     */
    public function loginRole(Request $request)
    {
        $data = $request->postData;
        $uuid = $data['uuid'] ?? '';
        $role_id = $data['role_id'] ?? 0;
        $job_id = $data['job_id'] ?? 0;
        $fight_cap = $data['fight_cap'] ?? 0;

        $user_model = Role::query()->where('uuid', $uuid)->where('role_id', $role_id)->first();
        if (empty($user_model)) {
            $user_model = new Role();
            $user_model->uuid = $uuid;
            $user_model->role_id = $role_id;
            $user_model->job_id = $job_id;
            $user_model->fight_cap = $fight_cap;
            $user_model->save();
        }

        return outJson(0, '创建成功！');
    }

    /***
     *
     * @param Request $request
     * @return Response
     */
    public function updateRoleInfo(Request $request)
    {
        $data = $request->postData;
        $uuid = $data['uuid'] ?? '';
        $role_id = $data['role_id'] ?? 0;
        $job_id = $data['job_id'] ?? 0;
        $fight_cap = $data['fight_cap'] ?? 0;
        $level = $data['level'] ?? 0;
        $gold = $data['gold'] ?? 0;
        $ingot = $data['ingot'] ?? 0;
        $exp = $data['exp'] ?? 0;
        $vip = $data['vip'] ?? 0;
        $data['gold_delta'] = $data['gold_delta'] ?? 0;
        $data['ingot_delta'] = $data['ingot_delta'] ?? 0;
        $data['ip'] = $request->getRealIp();

        $user_model = Role::query()->where('uuid', $uuid)->where('role_id', $role_id)->first();
        if ($user_model) {
            if ($fight_cap > 0) {
                $user_model->fight_cap = $fight_cap;
            }
            if ($level > 0) {
                $user_model->level = $level;
            }
            if ($gold > 0) {
                $user_model->gold = $gold;
            }
            if ($ingot > 0) {
                $user_model->ingot = $ingot;
            }
            if ($exp > 0) {
                $user_model->exp = $exp;
            }
            if ($job_id > 0 and $job_id != $user_model->job_id) {
                $user_model->job_id = $job_id;
            }
            if ($vip > 0) {
                $user_model->vip = $vip;
            }

            $user_model->save();

        } else {
            // 第一个角色发送首发福利
            if ($job_id > 0) {
                $is_create = Role::query()->where('uuid', $uuid)->exists();
                if (!$is_create) {
                    $mail = Mail::query()->where('uuid', $uuid)->where('title', '首发福利')->exists();
                    if (!$mail) {
                        $str = '[{"item_key":100000410,"num":5,"attrs":[]},{"item_key":100000392,"num":50,"attrs":[]},{"item_key":100000453,"num":1,"attrs":[]},{"item_key":100000402,"num":10,"attrs":[]},{"item_key":100000398,"num":20,"attrs":[]}]';
                        Mail::create([
                            'type' => Constant::MAIL_TYPE_2,
                            'uuid' => $uuid,
                            'role_id' => $role_id,
                            'title' => '首发福利',
                            'content' => '重回盟重，首发福利，账号下的第一个角色进游戏即可领取。',
                            'attach' => json_decode($str, true),
                        ]);
                        //预约奖励
                        // $this->yuyueAward($uuid, $role_id);
                    }
                }

                $user_model = new Role();
                $user_model->uuid = $uuid;
                $user_model->role_id = $role_id;
                $user_model->job_id = $job_id;
                $user_model->fight_cap = $fight_cap;
                $user_model->level = $level;
                $user_model->gold = $gold;
                $user_model->ingot = $ingot;
                $user_model->exp = $exp;
                $user_model->save();
            }
        }

        Redis::send(Constant::RECORD_USER_RES_LOG, $data);
        Redis::send(Constant::LEVEL_LOG, $data);

        return outJson(0, '创建成功！');
    }

    private function yuyueAward($uuid, $role_id)
    {
        $str1 = '[{"item_key":100000160,"num":100,"attrs":[]},{"item_key":100000064,"num":10,"attrs":[]},{"item_key":100000277,"num":10,"attrs":[]},{"item_key":100000372,"num":188,"attrs":[]}]';
        $str2 = '[{"item_key":100000278,"num":2,"attrs":[]},{"item_key":100000064,"num":20,"attrs":[]},{"item_key":100000277,"num":20,"attrs":[]},{"item_key":100000351,"num":1,"attrs":[]}]';
        $str3 = '[{"item_key":100000278,"num":3,"attrs":[]},{"item_key":100000064,"num":40,"attrs":[]},{"item_key":100000277,"num":30,"attrs":[]},{"item_key":100000288,"num":20,"attrs":[]}]';
        $str4 = '[{"item_key":100000278,"num":4,"attrs":[]},{"item_key":100000064,"num":80,"attrs":[]},{"item_key":100000277,"num":50,"attrs":[]},{"item_key":100000453,"num":1,"attrs":[]}]';
        Mail::create([
            'type' => Constant::MAIL_TYPE_2,
            'uuid' => $uuid,
            'role_id' => $role_id,
            'title' => '预约奖励1',
            'content' => '《重回盟重》预约人数达到 500 人次，首发上线，全服福利，所有玩家将获得如下奖励。',
            'attach' => json_decode($str1, true),
        ]);
        Mail::create([
            'type' => Constant::MAIL_TYPE_2,
            'uuid' => $uuid,
            'role_id' => $role_id,
            'title' => '预约奖励2',
            'content' => '《重回盟重》预约人数达到 1000 人次，首发上线，全服福利，所有玩家将获得如下奖励。',
            'attach' => json_decode($str2, true),
        ]);
        Mail::create([
            'type' => Constant::MAIL_TYPE_2,
            'uuid' => $uuid,
            'role_id' => $role_id,
            'title' => '预约奖励3',
            'content' => '《重回盟重》预约人数达到 2000 人次，首发上线，全服福利，所有玩家将获得如下奖励。',
            'attach' => json_decode($str3, true),
        ]);
        Mail::create([
            'type' => Constant::MAIL_TYPE_2,
            'uuid' => $uuid,
            'role_id' => $role_id,
            'title' => '预约奖励4',
            'content' => '《重回盟重》预约人数达到 3000 人次，首发上线，全服福利，所有玩家将获得如下奖励。',
            'attach' => json_decode($str4, true),
        ]);
    }


    /***
     *红点相关
     * @param Request $request
     * @return Response
     */
    public function redDot(Request $request)
    {
        $data = $request->postData;
        $uuid = $data['uuid'] ?? '';
        $role_id = $data['role_id'] ?? 0;

        $is_exists = $user_model = Mail::query()->where('uuid', $uuid)->where('role_id', $role_id)->where('is_read', 0)->exists();

        //邮件红点
        $out_data['email'] = intval($is_exists);
        return outJson(0, 'ok', $out_data);
    }

    public function recordItem(Request $request)
    {
        $data = $request->postData;
        $data['ip'] = $request->getRealIp();
        $uuid = $data['uuid'] ?? '';
        $role_id = $data['role_id'] ?? 0;
        $item_key = $data['item_key'] ?? 0;
        $num = $data['num'] ?? 1;

        // 队列名
        $queue = Constant::RECORD_ITEM;
        // 投递消息
        Redis::send($queue, $data);

        return outJson(0, 'ok');
    }

    public function exchangeLog(Request $request)
    {
        $data = $request->postData;
        $item_key = $data['item_key'] ?? '';
        $uuid = $data['uuid'] ?? '';
        $role_id = $data['role_id'] ?? '';
        $shop_items = Shop::getItems();

        $item_info = [];
        foreach ($shop_items as $shop_item) {
            if ($shop_item['物品key'] == $item_key) {
                $item_info = $shop_item;
                break;
            }
        }

        $get_times = UserExchangeLog::query()->where('item_key', $item_key)->count();
        if ($item_info['数量'] and intval($item_info['数量']) <= intval($get_times)) {
            return outJson(1, '兑换次数不足');
        }

        UserExchangeLog::create([
            'item_key' => $item_key,
            'uuid' => $uuid,
            'role_id' => $role_id,
        ]);

        return outJson(0, 'ok');
    }

    public function exchangeNum(Request $request)
    {
        $data = $request->postData;
        $uuid = $data['uuid'] ?? '';
        $role_id = $data['role_id'] ?? '';
        $shop_items = Shop::getItems();

        $_shop_items = [];
        foreach ($shop_items as $shop_item) {
            if ($shop_item['商店类型'] == 4) {
                $_shop_items[] = $shop_item;
            }
        }

        $item_keys = array_column($_shop_items, '物品key');

        $get_times = UserExchangeLog::query()->select("item_key", Db::raw("count(1) total_num"))->whereIn('item_key', $item_keys)->groupBy('item_key')->pluck('total_num', 'item_key');
        $get_times = $get_times ? $get_times->toArray() : [];

        // $get_times['100000451'] = 16;
        // $get_times['100000452'] = 88;


        $list = [];
        foreach ($_shop_items as $shop_item) {
            $list[$shop_item['物品key']] = $get_times[$shop_item['物品key']] ?? 0;
        }

        $outdata['list'] = $list;
        return outJson(0, 'ok', $outdata);
    }

    //全部踢下线
    public function checkKick(Request $request)
    {
        $data = $request->postData;
        $is_ban = User::query()->where('uuid', $data['uuid'])->value('is_ban');
        return outJson(0, 'ok', ['state' => intval($is_ban)]);
    }

    //全部踢下线
    public function resetClear(Request $request)
    {
        $data = $request->postData;
        User::query()->where('uuid', $data['uuid'])->update(['clear_role' => 0]);
        return outJson(0, 'ok');
    }


    public function setVip(Request $request)
    {
        $data = $request->postData;
        $uuid = $data['uuid'];
        $arr = [
            '97d862c5bc932aa1a7d98d286b6278c1343b1ab73db0ad25edea444b9d9f3804',
            '4c1dd6608fbcd9e2924369f65352cb346fad122e2f1a7769044716175ac0dc26',
            '0e722d39336691d0017059947b0b1a97f0d122bb2247003b614e13c08927e456',
            '327bce2e77168b2063e2381765d282ee69e8847b6a4e560bc2b3cdd4ef14415c',
            '3bb3a16bdee143d1c183ac0552d394f8a2f4e414af1cd3a3bf3b2f47add7a718',
            'e005273118fde75ce5d7f406805e622fb8e8b9ead9ea051036517477979eb2a2',
            '4b5fd8273ddac3221a690fbe555dc05f2d6f25aca0d597f6e4e49c88f4d396a7',
            'b31b5144ee4f0f87df4fef7f660a15da57b8cf276a6c8686d94387287e57de8b',
            'c91a84656f83a49573957189e99107ae69e9304a4572c6b9c70afbc9f5d7f90e',
            '4c99b05b252f58c315031c0c7bf3309efedff881592b22af056c62bf721063c0',
            '5c6ac1959274646a4c6ef636de906bb4850ee7591a9572a5486bb662cde25741',
            '3d09b2219a3f61f16452b87aedb1df1cea179e50edbe04950cd79ef2d732737d',
            'b92aced83fcb67a3b24a9032413753f3e0b8c9ab40a913a89445480e5b823e13',
            'fc4f01ac2f5e10c568f03de938ff30121fedda6b8b27090699a8f56d9bbdf249',
            '0281ed78a1d5f35e9eb715a1cb6d4f0d6ff1146c52fcad53784dc0764af50b28',
            'fa9914799203492280a4ff38967e191c714ebf195a7cfc8fc25510beeff5f86e',
            'd1be09a6362c19b9eddee485bf71f628e9c5ef1523f287449449214d631bee5e',
            '1f56bafec66a90112c42154447b4099b913e7b492e2912438f8659b3765e4990',
            '79bc1c3f4c4f45450bcbafc0a3636a29443e00bf3991e8b33723757a1cb0cb3c',
            '1d7d260a0cf038a9d841d0c531226aaca68c123024b94e0993172d07059a7bd7',
            'cafe1ea22273d3a72e2b09db373d22d264481adfa9aebae1c87d475b1352c027',
            '7a024f7b73c1ea5c9740ceebdbe2f3f49c9b2d31ea34e175d7d1c1146ae2e925',
            'be8e236ed61545c1d416857405763b1b5818201c29974f2ba5d1401d1382826e',
            '5c130871151c068f3b02d47e941027fdc4ac4938e62bff4815434052c3357782',
            '25e6225ebff9882ad8ded7f09e1c232d04a63e50eac135137bd9e465f2c2cf75',
            'c8524fd999659bcc5f85fca199898eb5161be9e29613aadb0a9c99d86259d373',
            '2bae620864a3336a9350f2fb74aa6762fe4b42c10f5fca07ef8edcb66a8144f1',
            'c270dc78d3ba33f15784c4be7a856813299867387d245dfdde3dad872409566a',
            'a488d5d739dbf680ec7ddf70813eecd3f261e27e7151b322646ba8cf32c70174',
            '0b462f9d1b84353b3a8cbb1a9f5039cbce4874649340cf88f88ce1a82bd659e5',
            'd6398513cadde9c1d0f95b5b08085920c7b8c99296b210f3419a7ebfeca08dfe',
            '69f54702fe7cdb427f721bdc28b3c06062447a4cde424f657489732871c948f3',
            '8daefdb1cbbac0e3db59822500ce10fe1ed76c4aa06bb9054cf5247943183d79',
            '3be2d333aa524cd29820e1cb591694c7259e3a8ae6966d40a315656152768ba2',
            'dd9d96bac66eacbafe1559c9ec0c87a53c47514cf3fb89b498c0ddfb4323dea2',
            '77d7de51620e15211aca4ea19d2bbcbd66686e1e502ecb3b03d37c79daafedce',
            'de508ba40bbfcc9d1e274cf48aaaca3721e965a08f93c727c5f077671d0d8bfb',
            '1f1b073a2ea28abf3bb437a7b8db27c1177f2c10724bbcc5cf371ec81d5b634c',
            '2b9678f84e0c099a00f1d707b4bedb508ff2c5842ce2be59ccfc23745ef44906',
            'c6f38731497f716b122b4250c26a540bb5d5d79237386f65af1f449087b3d7fb',
            'a505ee834c6b1c006df0b5875cbb82fd529299e005292408e641f0646ae165ca',
            'df32b0a7f449643d1a0fc766f369091f9ec03d7d0183724c99901a0a27cb9623',
            'dc16bcac473317f1f473fd5a1199de243e599379d9a46cd20f473830c8c6c569',
            '27ebff6900bef240bd50dbf9d379b56332096db8f685c0f9deffddabf5ea07f3',
            'f628d2649ab859a28b07437cd5de91aa5d9cbab13be97c45ddf08219033ababd',
            '195f41e3f9fd28fa3bd6d5744079a74ec2daa76df8b9138fb44c8554b931f9d2',
            '57c464b35275ffc601086af838fc23e1fd2ecd611a535396ecf98a25d6f3f753',
            'df41c589b6feb078cb01e2b6aa1d9287229119790b6f44c57a5cce210577feff',
            '4029a03998e690e5e842647ece6640cc6254bde7fb30230ff2007c6736409cb7',
            'f321e918c40456b7bd92cb369450d44f74025228520bec36d06a740c8f258265',
        ];

        // $arr = [
        //     'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
        // ];

        $key_index = array_search($uuid, $arr);
        $vip = 0;
        if ($key_index !== false) {
            $state = \support\Redis::get($uuid);
            if (empty($state)) {
                $rank = $key_index + 1;
                if ($rank >= 1 && $rank <= 3) {
                    $vip = 17;
                } elseif ($rank >= 4 && $rank <= 10) {
                    $vip = 15;
                } elseif ($rank >= 11 && $rank <= 50) {
                    $vip = 12;
                }
                \support\Redis::set($arr[$key_index], 1);
            }
        }
        return outJson(0, 'ok', ['vip' => $vip]);
    }


}
